<?php

namespace hamster\tools\com;

class Rsa
{
	private static $private_path = null; // 私钥地址
	private static $public_path = null; // 公钥地址


	public function __construct($private_path='', $public_path='')
	{
		self::$private_path = $private_path;
		self::$public_path = $public_path;
	}

	/**
	 * 获取私钥
	 * @return bool|resource
	 */
	private static function getPrivateKey()
	{
		if (!self::$private_path) return null;

		$content = file_get_contents(self::$private_path);
		return openssl_pkey_get_private($content);
	}

	/**
	 * 获取公钥
	 * @return bool|resource
	 */
	private static function getPublicKey()
	{
		if (!self::$public_path) return null;

		$content = file_get_contents(self::$public_path);
		return openssl_pkey_get_public($content);
	}

	/**
	 * 私钥加密
	 * @param string $data
	 * @return null|string
	 */
	public function privateEncrypt($data = '')
	{
		if (!is_string($data)) return null;
		if (!$private_key = self::getPrivateKey()) return false;

		return openssl_private_encrypt($data, $encrypted, $private_key) ? base64_encode($encrypted) : null;
	}

	/**
	 * 公钥加密
	 * @param string $data
	 * @return null|string
	 */
	public function publicEncrypt($data = '')
	{
		if (!is_string($data)) return null;
		if (!$public_key = self::getPublicKey()) return false;

		return openssl_public_encrypt($data, $encrypted, $public_key) ? base64_encode($encrypted) : null;
	}

	/**
	 * 私钥解密
	 * @param string $encrypted
	 * @return null
	 */
	public function privateDecrypt($encrypted = '')
	{
		if (!is_string($encrypted)) return null;
		if (!$private_key = self::getPrivateKey()) return false;

		return (openssl_private_decrypt(base64_decode($encrypted), $decrypted, $private_key)) ? $decrypted : null;
	}

	/**
	 * 公钥解密
	 * @param string $encrypted
	 * @return null
	 */
	public function publicDecrypt($encrypted = '')
	{
		if (!is_string($encrypted)) return null;
		if (!$public_key = self::getPublicKey()) return false;

		return (openssl_public_decrypt(base64_decode($encrypted), $decrypted, $public_key)) ? $decrypted : null;
	}
}
